<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue.directive 自定义指令</title>
  </head>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <body>
    <h1>Hello Vue.directive 自定义指令</h1>
    <hr />
    <div id="app">
      <div v-jspang="color">{{num}}</div>
      <p>
        <button @click="add">add</button>
      </p>
    </div>
    <button onclick="unbind()">解绑</button>
  </body>

  <script>
    /**
     * directive 回调函数有5个钩子函数
     *
     * bind：指令绑定时执行
     * inserted：元素被插入到父级元素时执行
     * update：组件更新时执行
     * componentUpdated：数据更新完成时执行
     * unbind：解绑时执行
     *
     */
    Vue.directive('jspang', {
      bind: function () {
        console.log('1 - bind')
      },
      inserted: function () {
        console.log('2 - inserted')
      },
      update: function () {
        console.log('3 - update')
      },
      componentUpdated: function () {
        console.log('4 - componentUpdated')
      },
      unbind: function () {
        console.log('5 - unbind')
      }
    })

    var app = new Vue({
      el: '#app',
      data: {
        num: 10,
        color: 'red'
      },
      methods: {
        add: function () {
          this.num++
        }
      }
    })

    function unbind () {
      app.$destroy()
    }
  </script>
</html>
